<template>
  <a-modal
    :open="open"
    width="640px"
    :title="rowData?.id ? '修改调价单' : '新增调价单'"
    centered
    :ok-button-props="{ disabled: !isCompleted }"
    ok-text="保存"
    @ok="onOk"
    @cancel="onCancel"
  >
    <a-form class="form-style-flex" name="validate_other" :model="formState">
      <a-form-item label="调价根据" class="w-full" v-bind="validateInfos.reason">
        <a-input v-model:value="formState.reason" placeholder="请输入" />
      </a-form-item>

      <a-form-item label="生效日期" class="w-full" v-bind="validateInfos.effectiveTime">
        <a-date-picker v-model:value="formState.effectiveTime" :disabled-date="disabledDate" class="w-full" placeholder="生效日期" value-format="YYYY-MM-DD" />
      </a-form-item>
      <a-form-item label="备注" class="w-full">
        <a-textarea v-model:value="formState.memo" :rows="6" placeholder="请输入" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { post } from '@/utils/request'

const router = useRouter()

const emit = defineEmits(['update:open', 'update:value', 'success'])
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  },
  title: {
    type: String,
    default: ''
  }
})

const formState = ref({
  reason: '',
  effectiveTime: '',
  memo: ''
})
const disabledDate = (current) => {
  // 获取今天的日期
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  // 将当前日期与今天的日期进行比较
  return current && current < today
}
const rulesState = ref({
  reason: [{ required: true, message: '请输入调价根据' }],
  effectiveTime: [{ required: true, message: '请选择生效日期' }]
})
const { isCompleted, resetFields, validate, validateInfos } = useForm(formState, rulesState)
watch(
  () => props.open,
  (val) => {
    if (val) {
      if (props.rowData?.id !== '') {
        formState.value = {
          ...props.rowData
        }
      }
    }
  }
)

const onOk = async () => {
  await validate()
  const formData = {
    id: formState.value.id || '',
    ...formState.value
  }
  const res = await post('drugStorage/comprehenive/doSavePriceAdjustmentHead', formData)
  if (res.code === 0) {
    message.success(res.msg)
    if (!formState.value?.id) {
      router.push({
        path: '/drug/price/adjust-detail',
        query: {
          id: res.data.id
        }
      })
    }

    emit('success')

    onCancel()
  } else {
    message.error(res.msg)
  }
}

const onCancel = () => {
  emit('update:open', false)
  resetFields()
}
</script>
<style lang="less" scoped></style>
